package com.xqyq.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xqyq.model.Match;

@Repository
public class MatchDao {
	@Autowired
	private SessionFactory sessionFactory;
	
	public boolean addMatch(Match match){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Match m where match_name=?");
		query.setString(0, match.getMatch_name());
		if(query.uniqueResult()==null){
			session.persist(match);
			return true;
		}
		else {
			return false;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Match> getAllMatch(){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Match m order by m.create_date desc");
		return query.list();
	}
	
	public void changeMatchState(int match_id,int state){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("update Match set state=? where match_id=?");
		query.setInteger(0, state);
		query.setInteger(1, match_id);
		query.executeUpdate();
	}
	
	public Match getMatch(int match_id){
		Session session = sessionFactory.getCurrentSession();
		return (Match) session.get(Match.class, match_id);
	}
	
	public void updateMatch(Match match){
		Session session = sessionFactory.getCurrentSession();
		session.update(match);
		session.update(match.getMatch_content());
	}
	
	public void deleteMatch(int match_id){
		Session session = sessionFactory.getCurrentSession();
		session.delete(session.load(Match.class, match_id));
	}
	
	@SuppressWarnings("unchecked")
	public List<Match> getPublishMatch(int limit){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Match m where state>0 order by m.create_date desc");
		query.setMaxResults(limit);
		return query.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Match> getEndMatch(){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Match m where state=3 order by m.create_date desc");
		query.setMaxResults(15);
		return query.list();
	}
	
	
}
